/***********************************************************************
    filename:   hgeGeometryBuffer.cpp
    created:    Mon Feb 9 2009
    author:     Paul D Turner
*************************************************************************/

#define NOMINMAX
#include "hgeGeometryBuffer.h"
#include "hgeTexture.h"
#include "hgeRenderEffect.h"
#include "hgeVertex.h"
#include <d3d9.h>
#include <d3dx9.h>

//----------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(LPDIRECT3DDEVICE9 device) :
    d_activeTexture(0),
    d_translation(0, 0, 0),
    d_rotation(0, 0, 0),
    d_pivot(0, 0, 0),
    d_effect(0),
    d_device(device),
    d_matrixValid(false)
{
}

//----------------------------------------------------------------------------//
void GeometryBuffer::draw() const
{
    // setup clip region
	RECT clip;
    clip.left   = static_cast<LONG>(d_clipRect.d_left);
    clip.top    = static_cast<LONG>(d_clipRect.d_top);
    clip.right  = static_cast<LONG>(d_clipRect.d_right);
    clip.bottom = static_cast<LONG>(d_clipRect.d_bottom);
    d_device->SetScissorRect(&clip);

    // apply the transformations we need to use.
    if (!d_matrixValid)
        updateMatrix();

    d_device->SetTransform(D3DTS_WORLD, &d_matrix);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches
        size_t pos = 0;
        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            d_device->SetTexture(0, (*i).first);
            d_device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, (*i).second / 3,
                                    &d_vertices[pos], sizeof(D3DVertex));
            pos += (*i).second;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setTranslation(const Vector3& t)
{
    d_translation = t;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setRotation(const Vector3& r)
{
    d_rotation = r;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setPivot(const Vector3& p)
{
    d_pivot = p;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setClippingRegion(const hgeRect& region)
{
    d_clipRect = region;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const Vertex& vertex)
{
    appendGeometry(&vertex, 1);
}

//----------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const Vertex* const vbuff,
                                             UINT vertex_count)
{
    performBatchManagement();

    // update size of current batch
    d_batches.back().second += vertex_count;

    // buffer these vertices
    D3DVertex vd;
    const Vertex* vs = vbuff;
    for (UINT i = 0; i < vertex_count; ++i, ++vs)
    {
        // copy vertex info the buffer, converting from Vertex to
        // something directly usable by D3D as needed.
        vd.x       = vs->position.d_x - 0.5f;
        vd.y       = vs->position.d_y - 0.5f;
        vd.z       = vs->position.d_z;
        vd.diffuse = vs->colour_val.getARGB();
        vd.tu      = vs->tex_coords.d_x;
        vd.tv      = vs->tex_coords.d_y;
        d_vertices.push_back(vd);
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setActiveTexture(Texture* texture)
{
    d_activeTexture = texture;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::reset()
{
    d_batches.clear();
    d_vertices.clear();
    d_activeTexture = 0;
}

//----------------------------------------------------------------------------//
Texture* GeometryBuffer::getActiveTexture() const
{
    return d_activeTexture;
}

//----------------------------------------------------------------------------//
UINT GeometryBuffer::getVertexCount() const
{
    return d_vertices.size();
}

//----------------------------------------------------------------------------//
UINT GeometryBuffer::getBatchCount() const
{
    return d_batches.size();
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* GeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::performBatchManagement()
{
    const LPDIRECT3DTEXTURE9 t = d_activeTexture ?
                                 d_activeTexture->getTexture() : 0;

    // create a new batch if there are no batches yet, or if the active texture
    // differs from that used by the current batch.
    if (d_batches.empty() || (t != d_batches.back().first))
        d_batches.push_back(BatchInfo(t, 0));
}

//----------------------------------------------------------------------------//
void GeometryBuffer::updateMatrix() const
{
    const D3DXVECTOR3 p(d_pivot.d_x, d_pivot.d_y, d_pivot.d_z);
    const D3DXVECTOR3 t(d_translation.d_x, d_translation.d_y, d_translation.d_z);

    D3DXQUATERNION r;
    D3DXQuaternionRotationYawPitchRoll(&r,
        D3DXToRadian(d_rotation.d_y),
        D3DXToRadian(d_rotation.d_x),
        D3DXToRadian(d_rotation.d_z));

    D3DXMatrixTransformation(&d_matrix, 0, 0, 0, &p, &r, &t);

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
const D3DXMATRIX* GeometryBuffer::getMatrix() const
{
    if (!d_matrixValid)
        updateMatrix();

    return &d_matrix;
}

//----------------------------------------------------------------------------//
